from django.shortcuts import render
from rest_framework import viewsets
from .models import Menus, Image, Message, LabelType, CurrencyLabel
from .serializers import MenusSerializer, ImageSerializer, MessageSerializer, LabelTypeSerializer, \
    CurrencyLabelSerializer, CompanyMessageSerializer
from .filter import MessageFilter, CurrencyLabelFilter
from utils.response_util import VueAPIResponse, APIResponse
from utils.common_util import pre_menus
from server.utils import check_group_id
from django.db.models import Q
# 分页
from utils.pagination_util import PageNumberPaginationUtil

from django.conf import settings


class MenuViewSet(viewsets.ModelViewSet):
    queryset = Menus.objects.all()
    serializer_class = MenusSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = self.get_serializer(queryset, many=True)

        menus = pre_menus(queryset.data)
        return VueAPIResponse(self, queryset, data=menus)

    # def create(self, request, *args, **kwargs):
    #     form = request.data.get('origin', 'mobile')
    #     username = request.data.get('username')
    #     code = request.data.get('code')
    #     password = request.data.get('password')
    #     re_password = request.data.get('re_password')
    #     reg_type = request.data.get("reg_type", 0)
    #
    #     try:
    #         if form == 'mobile':
    #             record = PhoneCaptcha.objects.get(phone=username, code=code)
    #             if int(time.time()) - int(record.send_time) > tencent_sms_time_out:
    #                 raise SmsTimeOutError
    #
    #         # 检查两次密码是否一致
    #         if password != re_password:
    #             raise PasswordError("两次密码不一致")
    #
    #         # 检查用户名是否已经存在
    #         if User.objects.filter(username=username).exists():
    #             raise AccountHasBeenExistError
    #
    #         # 创建新用户对象
    #         user = User.objects.create(username=username)
    #
    #         # 设置用户密码
    #         user.set_password(password)
    #         user.save()
    #
    #         # 同时在角色表添加一条信息
    #         if reg_type == 0:  # 普通用户
    #             user_role = UserRole.objects.create(user_id=user.id, role_id=1)
    #             user_role.save()
    #         elif reg_type == 1:  # 公司员工
    #             user_role = UserRole.objects.create(user_id=user.id, role_id=2)
    #             user_role.save()
    #         elif reg_type == 2:  # 公司管理员
    #             user_role = UserRole.objects.create(user_id=user.id, role_id=3)
    #             user_role.save()
    #
    #         return Response({'status': 'success'}, status=status.HTTP_201_CREATED)
    #
    #     except PhoneCaptcha.DoesNotExist:
    #         raise SmsError("验证码错误")
    #
    #     except PasswordError as e:
    #         raise PasswordError(str(e))
    #
    #     except Exception as e:
    #         # 处理其他可能的异常
    #         return Response({'status': 'error', 'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ImageViewSet(viewsets.ModelViewSet):
    """（素材库）图片"""
    queryset = Image.objects.filter(type='image').values()
    serializer_class = ImageSerializer
    conditions = 'Image'

    # 识别上传文件类型
    def create(self, request, *args, **kwargs):
        # 获取上传的文件类型
        file_type = request.FILES['url'].content_type
        # 根据文件类型更新is_image字段的值
        if file_type.startswith('image/'):
            request.data['type'] = 'image'
        elif file_type.startswith('video/'):
            request.data['type'] = 'video'

        return super().create(request, *args, **kwargs)

    # 重写方法
    def get_serializer_context(self):
        return {
            # 'request':self.request,
            'format': self.format_kwarg,
            'view': self
        }


class MessageViewSet(viewsets.ModelViewSet):
    """平台消息"""
    queryset = Message.objects.filter(type=0)
    serializer_class = MessageSerializer
    filterset_class = MessageFilter
    search_fields = ['content', 'title']
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        title = request.GET.get('title')
        if title:
            queryset = queryset.filter(
                Q(title__icontains=title) | Q(content__icontains=title))

        serializer = self.get_serializer(queryset, many=True)
        return VueAPIResponse(self, queryset, data=serializer.data)


class CompanyMessageViewSet(viewsets.ModelViewSet):
    """公司消息"""
    queryset = Message.objects.filter(type=1)
    serializer_class = CompanyMessageSerializer
    filterset_class = MessageFilter
    search_fields = ['content', 'title']
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        if check_group_id(self.request.user.group_id) == 'super_admin':
            queryset = self.filter_queryset(self.get_queryset())
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            queryset = self.filter_queryset(self.get_queryset().filter(company_id=self.request.user.company_id))

        serializer = self.get_serializer(queryset, many=True)
        return VueAPIResponse(self, queryset, data=serializer.data)


class LabelTypeViewSet(viewsets.ModelViewSet):
    """通用标签类型"""
    queryset = LabelType.objects.all()
    serializer_class = LabelTypeSerializer
    # permissions = permissions.IsAdminUser
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        search = request.GET.get('search')
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search))

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)


class CurrencyLabelViewSet(viewsets.ModelViewSet):
    """通用标签"""
    queryset = CurrencyLabel.objects.all().order_by('order', 'name')
    serializer_class = CurrencyLabelSerializer
    pagination_class = PageNumberPaginationUtil
    filterset_class = CurrencyLabelFilter

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        # name = request.GET.get('name')
        label_type = request.GET.get('label_type')
        # if name:
        #     queryset = queryset.filter(
        #         Q(name__icontains=name))
        if label_type:
            queryset = queryset.filter(
                Q(type=label_type))

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)
    # def get_permissions(self):
    #     """授权"""
    #     if self.action == 'list' or self.action == 'partial_update' or self.action == 'destroy':
    #         return [permissions.IsAuthenticated()]
    #     else:
    #         return [permissions.IsAdminUser()]

    # def destroy(self, request, *args, **kwargs):
    #     label = self.get_object()
    #     if label.name == "无标签" and label.count_image():
    #         raise serializers.ValidationError("【无标签】内有图片，请先移除图片再删除")
    #     else:
    #         label.delete()
    #         return Response(data="删除成功！")
